/**
 *    TimedProfiles - let Android perform tasks based on conditions
 *    Copyright (C) 2011  Daniel Weinhold
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * */
package de.drak.Profiles.plugins;

import de.drak.Profiles.OnlineHelp;
import de.drak.Profiles.R;
import de.drak.Profiles.TimedProfiles;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.RadioButton;
import android.widget.AdapterView.OnItemSelectedListener;


/**Used to Edit a Date Condition
 * Current Weekday
 * Calendar entry
 * */
public class DatePicker extends Activity {


	private static final int MENU_SAVE = 1;
	private static final int MENU_DONT_SAVE = 2;
	static final int DAY_DIALOG_ID = 1;
	static final int WORD_DIALOG_ID = 2;
	static final String STORE_STAT = "date.stat";
	static final String STORE_CAL_WORDS = "date.calendar.words";
	static final String STORE_CAL_ID = "date.calendar.id";
	static final String STORE_DAYS = "date.weekdays";


	/**Indicates if Activity should return RESULT_CANCELED*/
	private boolean isCancelled;
	private int[] mWeekdays;
	private int mCalendar;
	private String[] mCalendarWords;
	private String StatCode;
	
    private OnClickListener ListButtons = new OnClickListener() {
        public void onClick(View v) {
        	switch(v.getId())
        	{
        		case R.id.RadioDays:
        			showDialog(DAY_DIALOG_ID);
        			break;
        		case R.id.RadioWord:
        			showDialog(WORD_DIALOG_ID);
        			break;
        	}
        }
    };
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void onCreate(final Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);

		daynames = new String[]{
	    		getString(R.string.plugin_datepicker_mo),
	    		getString(R.string.plugin_datepicker_di),
	    		getString(R.string.plugin_datepicker_mi),
	    		getString(R.string.plugin_datepicker_do),
	    		getString(R.string.plugin_datepicker_fr),
	    		getString(R.string.plugin_datepicker_sa),
	    		getString(R.string.plugin_datepicker_so)
	    };
		
		setContentView(R.layout.datepicker);
		findViewById(R.id.RadioDays).setOnClickListener(ListButtons);
		findViewById(R.id.RadioWord).setOnClickListener(ListButtons);

        //load title
		TimedProfiles.createTitle(this, getString(R.string.plugin_datepicker));

		/*
		 * if savedInstanceState == null, then we are entering the Activity directly and we need to check whether the
		 * Intent has forwarded a Bundle extra (e.g. whether we editing an old condition or creating a new one)
		 */
		if (savedInstanceState == null)
		{
			//some inits
	        mWeekdays = null;
	        mCalendarWords = null;
	        
			final Bundle forwardedBundle = getIntent().getBundleExtra(QueryReceiver.INTENT_BUNDLE);

			if (forwardedBundle == null)
			{
				//new
				showDialog(DAY_DIALOG_ID);
				((RadioButton) findViewById(R.id.RadioDays)).setChecked(true);
			}else{
				//loaded
				StatCode = forwardedBundle.getString(STORE_STAT);
				RadioButton rad = null;
				if(forwardedBundle.containsKey(STORE_DAYS))
				{
					//weekdays
					rad = (RadioButton) findViewById(R.id.RadioDays);
					mWeekdays = forwardedBundle.getIntArray(STORE_DAYS);
					
				}else if(forwardedBundle.containsKey(STORE_CAL_ID))
				{
					//words
					rad = (RadioButton) findViewById(R.id.RadioWord);
					mCalendar = forwardedBundle.getInt(STORE_CAL_ID);
					mCalendarWords = forwardedBundle.getStringArray(STORE_CAL_WORDS);
				}
				rad.setChecked(true);
				rad.setText(StatCode);
			}
		}
		/*
		 * if savedInstanceState != null, there is no need to restore any Activity state directly (e.g. onSaveInstanceState()).
		 * This is handled by the Spinner automatically
		 */
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void finish()
	{
		if (isCancelled)
			setResult(RESULT_CANCELED);
		else
		{

			/**return Intent, into which we'll put all the required extras*/
			final Intent returnIntent = new Intent();

			/**Data that will be stored*/
			final Bundle storeAndForwardExtras = new Bundle();

			if(((RadioButton) findViewById(R.id.RadioDays)).isChecked())
			{
				//weekdays
				if(mWeekdays == null)
				{
					setResult(TimedProfiles.RESULT_REMOVE);
					super.finish();
					return;
				}
				if(mWeekdays.length==0 || mWeekdays.length==7)
				{
					setResult(TimedProfiles.RESULT_REMOVE);
					super.finish();
					return;
				}
				storeAndForwardExtras.putIntArray(STORE_DAYS, mWeekdays);
			}else if(((RadioButton) findViewById(R.id.RadioWord)).isChecked())
			{
				//words
				if(mCalendarWords == null)
				{
					setResult(TimedProfiles.RESULT_REMOVE);
					super.finish();
					return;
				}
				storeAndForwardExtras.putInt(STORE_CAL_ID, mCalendar);
				storeAndForwardExtras.putStringArray(STORE_CAL_WORDS, mCalendarWords);
			}else{
				//nothing
				setResult(TimedProfiles.RESULT_REMOVE);
				super.finish();
				return;
			}

			storeAndForwardExtras.putString(STORE_STAT, StatCode);
			storeAndForwardExtras.putInt(QueryReceiver.TYPE_FIELD, QueryReceiver.IS_DATE);
			returnIntent.putExtra(TimedProfiles.INTENT_INFO_STR, StatCode);
			returnIntent.putExtra(QueryReceiver.INTENT_BUNDLE, storeAndForwardExtras);

			setResult(RESULT_OK, returnIntent);
		}

		super.finish();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean onCreateOptionsMenu(final Menu menu)
	{
		super.onCreateOptionsMenu(menu);

		final Intent helpIntent = new Intent(this, OnlineHelp.class);
		helpIntent.putExtra("com.twofortyfouram.locale.intent.extra.HELP_URL", OnlineHelp.HELP_URL_PRE+"plugin/DatePicker");

		// Note: title set in onCreate
		helpIntent.putExtra(TimedProfiles.INTENT_TITLE, getTitle());

		menu.add(R.string.onlinehelp)
			.setIcon(android.R.drawable.ic_menu_help).setIntent(helpIntent);
		menu.add(0, MENU_DONT_SAVE, 0, android.R.string.cancel)
			.setIcon(android.R.drawable.ic_menu_close_clear_cancel).getItemId();
		menu.add(0, MENU_SAVE, 0, R.string.plugin_save)
			.setIcon(android.R.drawable.ic_menu_save).getItemId();
		return true;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean onMenuItemSelected(final int featureId, final MenuItem item)
	{
		switch (item.getItemId())
		{
			case MENU_SAVE:
			{
				finish();
				return true;
			}
			case MENU_DONT_SAVE:
			{
				isCancelled = true;
				finish();
				return true;
			}
		}

		return super.onOptionsItemSelected(item);
	}
    @Override    
    protected Dialog onCreateDialog(int id) 
    {
        switch (id) {
            case DAY_DIALOG_ID:
            	return new DayPickerDialog(this, mDaySetListener, mWeekdays);
            case WORD_DIALOG_ID:
            	return new WordPickerDialog(this, mWordSetListener, mCalendarWords);
        }
        return null;    
    }
  //grab the days from dialog
    private DialogInterface.OnCancelListener mDaySetListener =
        new DialogInterface.OnCancelListener() 
        {
			@Override
			public void onCancel(DialogInterface dialog) {
				mWeekdays = ((DayPickerDialog)dialog).days;
				StatCode = getString(R.string.plugin_datepicker_days_pre)+" ";
				int x = 0;
				while(x<mWeekdays.length)
				{
					StatCode = StatCode.concat(daynames[mWeekdays[x]]+", ");
					++x;
				}
				StatCode = StatCode.substring(0, StatCode.length()-2);
				((RadioButton) findViewById(R.id.RadioDays) ).setText(StatCode);
			}
        };
    //grab calendar settings from dialog
    private DialogInterface.OnCancelListener mWordSetListener =
        new DialogInterface.OnCancelListener() 
        {
			@Override
			public void onCancel(DialogInterface dialog) {
				
				mCalendar = ((WordPickerDialog)dialog).CalID;
				mCalendarWords = ((WordPickerDialog)dialog).CalWords;
				StatCode = ((WordPickerDialog)dialog).CalName+": ";
				int x = 0;
				while(x<mCalendarWords.length)
				{
					StatCode = StatCode.concat(mCalendarWords[x]+", ");
					++x;
				}
				StatCode = StatCode.substring(0, StatCode.length()-2);
				
				((RadioButton) findViewById(R.id.RadioWord) ).setText(StatCode);
			}
        };
    /*
    @Override
    protected void onResume() {
        super.onResume();
        //hope this is trigered after the dialog
        findViewById(R.id.RadioDate);
    }*/
    private String[] daynames; 
    private class DayPickerDialog extends AlertDialog
    {
    	public int[] days;
    	TableLayout main;
    	
    	DayPickerDialog(Context c, DialogInterface.OnCancelListener list, int[] go)
    	{
    		super(c);
    		main = new TableLayout(c);
    		TableRow row = new TableRow(c);
    		ToggleButton tg;
    		//show a toggle button for each day
    		int x = 0;
    		while(x<7)
    		{
    			tg= new ToggleButton(c);
        		tg.setText(daynames[x]);
        		tg.setTextOff(daynames[x]);
        		tg.setTextOn(daynames[x]);
        		row.addView(tg);
        		if(x==2)
        		{
            		main.addView(row);
            		row = new TableRow(c);
        		}
        		++x;
    		}
    		main.addView(row);
    		
    		//check the buttons that are (pre-)selected
    		if(go!=null)
    		{
	    		for(int buff : go)
    			{
	    			((ToggleButton)((ViewGroup)((ViewGroup)main).getChildAt(buff>=3?1:0)).getChildAt(buff>=3?buff-3:buff)).setChecked(true);
    			}
    		}
    		days=go;
    		
        	this.setButton(BUTTON_POSITIVE, getString(android.R.string.ok), new DialogInterface.OnClickListener() {
 	           public void onClick(DialogInterface dialog, int id) {
	        	   dialog.cancel();
	           }
	       });
        	this.setButton(BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
 	           public void onClick(DialogInterface dialog, int id) {
	                dialog.dismiss();
	           }
	       });
        	this.setCancelable(true);
        	this.setView(main);
        	this.setIcon(android.R.drawable.ic_popup_sync);
        	this.setTitle(R.string.plugin_datepicker_days);
        	this.setOnCancelListener(list);
    	}
    	/**
    	 * Save the Selected Days in a easy accessible Way
    	 * */
    	@Override
		public void cancel()
    	{
    		int[] buffer = new int[7];
    		int buff = 0;
    		int x = 0;
    		while(buff<7)
    		{
    			if( ((ToggleButton)((ViewGroup)((ViewGroup)main).getChildAt(buff>=3?1:0)).getChildAt(buff>=3?buff-3:buff)).isChecked() )
    			{
    				buffer[x] = buff;
    				++x;
    			}
    			++buff;
    		}
    		days = new int[x];
			System.arraycopy(buffer, 0, days, 0, x);
    		super.cancel();
    	}    	
    	
    }
    private class WordPickerDialog extends AlertDialog
    {
    	private TableLayout main;
    	private int[] CalendarIDs;
    	private String[] names;
    	public String CalName;
    	public int CalID;
    	public String[] CalWords;
    	
    	/**
    	 * Called when the DEL Button is hit
    	 * */
    	private final View.OnClickListener TextRemover = new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				ViewGroup dad = (ViewGroup) v.getParent().getParent();
				dad.removeView((View) v.getParent());
			}};
			
			/**
			 * Creates a Table row with a Text field and a DEL Button for it
			 * */
		private View BuildRow(Context c, String txt)
		{
    		TableRow row = new TableRow(c);
    		EditText TextBox = new EditText(c);
    		ImageView add = new ImageView(c);
    		add.setImageResource(android.R.drawable.ic_delete);
			add.setOnClickListener(TextRemover);
			
    		if(txt!=null)
    		{
    			TextBox.setText(txt);
    		}
    		row.addView(TextBox);
    		row.addView(add);
			return row;
		}
    	
    	WordPickerDialog(Context c, DialogInterface.OnCancelListener list, String[] bla)
    	{
    		super(c);
    		main = new TableLayout(c);
    		//first line: dropdown to select calendar ID
    		TableRow row = new TableRow(c);
    		Spinner dropdown = new Spinner(c);
    		row.addView(dropdown);
    		main.addView(row);
    		//second line: box to select only busy events
    		row = new TableRow(c);
    		CheckBox check = new CheckBox(c);
    		check.setText(R.string.plugin_datepicker_cal_busy);
    		
    		check.setEnabled(false);//TODO
    		
    		row.addView(check);
    		main.addView(row);
    		//text fields
			row = new TableRow(c);
    		EditText TextBox = new EditText(c);
    		ImageView add = new ImageView(c);
    		//first text field has a ADD Button and a hint
    		TextBox.setHint(R.string.plugin_datepicker_cal_hint);
    		add.setImageResource(android.R.drawable.ic_input_add);
			add.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					ViewGroup dad = (ViewGroup) v.getParent().getParent();
					int x = dad.indexOfChild(v);
					dad.addView(BuildRow(v.getContext(),null), x);
				}});
    		if(bla!=null && bla.length>0)
    		{
    			//if there is already text...
    			TextBox.setText(bla[0]);
    		}
    		row.addView(TextBox);
    		row.addView(add);
    		main.addView(row);

    		//if there is more text than one row, create the others
			int x = 1;
			while(bla!=null && x<bla.length){
	    		main.addView(BuildRow(c,bla[x]));
	    		++x;
    		}
    		
    		
        	this.setButton(BUTTON_POSITIVE, getString(android.R.string.ok), new DialogInterface.OnClickListener() {
 	           public void onClick(DialogInterface dialog, int id) {
	        	   dialog.cancel();
	           }
	       });
        	this.setButton(BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() {
 	           public void onClick(DialogInterface dialog, int id) {
	                dialog.dismiss();
	           }
	       });
        	this.setCancelable(true);
        	ScrollView scr = new ScrollView(c);
        	scr.addView(main);
        	this.setView(scr);
        	this.setIcon(android.R.drawable.ic_dialog_dialer);
        	this.setTitle(R.string.plugin_datepicker_words);
        	this.setOnCancelListener(list);
        	
        	//load the calendar names fo the dropdown
        	final Cursor cursor = c.getContentResolver().query(Uri.parse("content://calendar/calendars"),
        	 												(new String[] { "_id", "displayName" }), null, null, null);
        	 
        	if(cursor==null)
        	{
        		names = new String[1];
        		CalendarIDs = new int[1];
        	}else{
        		names = new String[1+cursor.getCount()];
        		CalendarIDs = new int[1+cursor.getCount()];
        		x = 1;
	        	while (cursor.moveToNext()) {
	        	 
	        		CalendarIDs[x] = cursor.getInt(0);
	        		names[x] = cursor.getString(1);
	        		x++;
	        	}
	        	cursor.close();
        	}
        	//first entry is always "all"
        	CalendarIDs[0] = 0;
        	names[0] = getString(R.string.plugin_datepicker_cal_all); 
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(c, android.R.layout.simple_spinner_item, names);
        	
        	dropdown.setAdapter(adapter);
        	dropdown.setOnItemSelectedListener(new OnItemSelectedListener()
                {
        			@Override
                    public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) 
                    {
        				CalID = arg0.getSelectedItemPosition();
                    }
         
					@Override
                    public void onNothingSelected(AdapterView<?> arg0) {}
                });

    	}
    	/**
    	 * Saves the Calendar ID, Name and the Keywords in a easy accessible Way
    	 * */
    	@Override
		public void cancel()
    	{
    		CalName = names[CalID];
    		int x = main.getChildCount()-3;//-2 wegen offset bis erster textbox
    		CalWords = new String[x+1];
    		while(x>=0)
    		{
    			CalWords[x] = String.format("%s", ((TextView) ((ViewGroup) main.getChildAt(x+2)).getChildAt(0)).getText());
    			--x;
    		}
    		super.cancel();
    	}    	
    	
    }
}
